package com.xie.springCloud.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.xie.springCloud.pojo.Dept;
import com.xie.springCloud.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

//restFull 风格请求
@RestController
public class DeptController {

    @Autowired private DeptService deptService;

    @Autowired private DiscoveryClient client;

    @PostMapping({"/dept/add"})
    public boolean addDept(Dept dept){
        return deptService.addDept(dept);
    }

    @GetMapping("/dept/get/{id}")
    //熔断，防止报错报异常
    @HystrixCommand(fallbackMethod="hyStrixGetById")
    public Dept getById(@PathVariable("id") Long id){
        Dept dept = deptService.getById(id);
        if(dept==null){
            throw new RuntimeException("找不到ID");
        }
        return dept;
    }

    public Dept hyStrixGetById(@PathVariable("id") Long id){
        return new Dept().setId(id).setName("no find data in mySql");
    }

    @GetMapping("/dept/list")
    public List<Dept> getList(){
        return deptService.getList();
    }

    @GetMapping("/dept/discovery")
    public Object discovery(){
        List<ServiceInstance> list = client.getInstances("springCloud_provider_dept"); //对应spring.application.name:
        for (ServiceInstance serviceInstance : list) {
            System.out.println(
                    serviceInstance.getHost()+"\t"+
                    serviceInstance.getInstanceId()+"\t"+
                    serviceInstance.getPort()+"\t"+
                    serviceInstance.getUri()
            );
        }
        return client;
    }
}
